import {
  _decorator,
  CCInteger,
  Component,
  Node,
  Animation,
  Collider2D,
  Contact2DType,
  Sprite,
  Game,
  AudioClip,
} from 'cc'
import { Bullet } from './Bullet'
import { GameManager } from './GameManager'
import { AudioMgr } from './AudioMgr'
const { ccclass, property } = _decorator

@ccclass('Enemy')
export class Enemy extends Component {
  @property({ type: CCInteger })
  speed: number = 200

  @property({ type: Animation })
  animation: Animation = null

  @property({ type: CCInteger })
  hp: number = 1

  @property({ type: CCInteger })
  score: number = 100

  @property
  animationHit: string = ''
  @property
  animationDown: string = ''

  // 敌机死亡音效
  @property({ type: AudioClip })
  enemyDownSound: AudioClip = null

  private _collider: Collider2D = null

  start() {
    this._collider = this.node.getComponent(Collider2D)
    if (this._collider) {
      this._collider.on(Contact2DType.BEGIN_CONTACT, this.onBegainContact, this)
    }
  }

  update(deltaTime: number) {
    if (this.hp > 0) {
      const { position } = this.node
      this.node.setPosition(position.x, position.y - this.speed * deltaTime, position.z)
      if (position.y < -570) {
        this.node.destroy()
      }
    }
  }
  onBegainContact(selfCollider: Collider2D, otherCollider: Collider2D) {
    if (otherCollider.getComponent(Bullet)) {
      otherCollider.enabled = false
      otherCollider.getComponent(Sprite).enabled = false
    }
    this.hp -= 1
    if (this.hp > 0) {
      this.animation.play(this.animationHit)
    } else {
      selfCollider.enabled = false
      this.enemyDead()
    }
  }
  enemyDead() {
    AudioMgr.inst.playOneShot(this.enemyDownSound, 1)
    this.animation.play(this.animationDown)
    GameManager.getInstance().addScore(this.score)
    this.scheduleOnce(() => {
      this.node.destroy()
    }, 1)
  }
  protected onDestroy(): void {
    if (this._collider) {
      this._collider.off(Contact2DType.BEGIN_CONTACT, this.onBegainContact, this)
    }
  }
}
